package my.test.map.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import my.test.map.data.PMF;
import my.test.map.data.logRecord;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.apphosting.api.ApiProxy.LogRecord;
import com.google.gson.Gson;

public class locationInfoServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1945748254218194331L;
	private String toJson(User user){
		return String.format("{\"id\":\"%s\",\"nickname\":\"%s\",\"email\":\"%s\"}"
				,user.getUserId(), user.getNickname(), user.getEmail());
	}

	private static final String SQL_LOG_QUERY = "select from " + LogRecord.class.getName();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        if(null != user){
    		PersistenceManager pm =null;
    		try{
        		pm = PMF.get().getPersistenceManager();
        		List<logRecord> records = (List<logRecord>) pm.newQuery("select from "  + logRecord.class.getName()).execute();
        		StringBuilder itms = new StringBuilder();
        		for(logRecord record : records){
        			if(itms.length() > 0){
        				itms.append(",");
        			}
        			Gson gson = new Gson();
        			itms.append(gson.toJson(record));
        		}
        		resp.setContentType("application/json");
        		resp.setCharacterEncoding("utf-8");
        		resp.getWriter().println(String.format("{\"numRows\":%d,\"items\":[%s]}", records.size(), itms.toString()));    			
    		}finally{
    			if(null != pm){
    				pm.close();
    			}
    		}

    	}else{
            resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
    	}

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		InputStream is = null;
		BufferedReader br = null;
		PersistenceManager pm = null;
		try{
			is = req.getInputStream();
			br = new BufferedReader(new InputStreamReader(is, "utf-8"));
			Gson gson = new Gson();
			logRecord rec = gson.fromJson(br, logRecord.class);
			
			UserService userService = UserServiceFactory.getUserService();
	        User user = userService.getCurrentUser();
	        rec.setAuthor(user);
	        rec.setCreated(new Date());
	        
	        pm = PMF.get().getPersistenceManager();
			
			pm.makePersistent(rec);
		}finally{
			if(null != br){
				br.close();
			}
			if(null != is){
				is.close();
			}
			if(null != pm){
				pm.close();
			}
		}
	}
	@Override
	protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        PersistenceManager pm = null;
        
        try{
        	pm = PMF.get().getPersistenceManager();
        	///delete records here...
        	pm.deletePersistentAll(pm.newQuery("select from "  + logRecord.class.getName()).execute());
        }finally{
        	if(null != pm){
        		pm.close();
        	}
        }
	}

}
